<template>
  <!--经理 - 挂账审批 -->
  <div class="jeecg-basic-table jeecg-basic-table-form-container">
    <a-form @keyup.enter.native="searchQuery">
      <a-row :gutter="8" type="flex">
        <a-col flex="153px">
          <a-form-item label="部门" :label-col="{ style: { width: '44px' } }" >
            <JDictSelectTag
              v-model:value="queryParam.ddlxIds"
              mode="multiple"
              dictCode="ddlxType@ddlxUser"
              placeholder="全部"
              :maxTagCount="0"
              :getPopupContainer="(node) => node.parentNode"
              :dropdownStyle="{ width: '120px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
            />
          </a-form-item>
        </a-col>

        <a-col flex="315px">
          <a-form-item label="日期" :label-col="{ style: { width: '40px' } }" >
            <a-date-picker
              v-model:value="queryParam.beginDate"
              :disabled-date="disabledStartDate"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 123px"
            />
            ~
            <a-date-picker
              v-model:value="queryParam.endDate"
              :disabled-date="disabledEndDate"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 123px"
            />
          </a-form-item>
        </a-col>

        <a-col flex="110px">
          <a-form-item label="状态" :label-col="{ style: { width: '40px' } }" >
            <a-select name="stat" id="stat" v-model:value="queryParam.stat" placeholder="全部" :showArrow="false" :allowClear="true">
              <a-select-option value="1">未审</a-select-option>
              <a-select-option value="9">回退</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col flex="185px">
          <a-form-item label="订单号" :label-col="{ style: { width: '60px' } }">
            <a-input placeholder="" v-model:value="queryParam.orderId" ></a-input>
          </a-form-item>
        </a-col>

        <a-col flex="230px">
          <a-form-item label="订单名称" :label-col="{ style: { width: '65px' } }">
            <a-input placeholder="" v-model:value="queryParam.travelLine" ></a-input>
          </a-form-item>
        </a-col>

        <a-col flex="80px">
          <a-form-item label="精确查" :label-col="{ style: { width: '53px' } }">
            <a-input type="checkbox" style="margin-top: 6px"/>
            <input type="hidden" name="account.jqchecked"/>
          </a-form-item>
        </a-col>

        <a-col flex="auto" style="float:right; width:100px;">
          <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
            <a-button type="primary" @click="searchQuery" preIcon="ant-design:search">查询</a-button>
          </span>
        </a-col>
      </a-row>
      <a-row :gutter="8">
        <!--a-col flex="110px">
          <a-form-item label="方式" :label-col="{ style: { width: '40px' } }" >
            <a-select name="sffs" id="sffs" v-model:value="queryParam.sffs" placeholder="全部" :showArrow="false" :allowClear="true">
              <a-select-option value="3">挂账</a-select-option>
              <a-select-option value="4">划转</a-select-option>
            </a-select>
          </a-form-item>
        </a-col-->
        <a-col flex="464px">
          <a-form-item label="采购单位" :label-col="{ style: { width: '66px' } }">
            <Cascader v-model:value="cascader.ids" :options="cascader.options" placeholder="请选择" stringToNumber @change="cooperatorSelect" :show-search="{ filter }"/>
          </a-form-item>
        </a-col>

        <a-col flex="150px">
          <view style="float: left; height: 28px; line-height: 28px">已选中 {{selectedRowKeys.length}} 条</view>
        </a-col>

        <a-col flex="auto" style="float:right; width:180px;">
          <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
            <a-button type="primary" color="success" @click="auditALLSelect" preIcon="ant-design:tags-twotone">提交</a-button>
            <!--a-button type="primary" color="error" @click="handAccountFlowTakeDataGrid('9')" preIcon="ant-design:project-outlined" style="margin-left: 8px">回退</a-button>
            <a-badge :count="backCn" :overflowCount="9" style="position:absolute;top:-3px;right:-2px"></a-badge-->
          </span>
        </a-col>
      </a-row>
    </a-form>
  </div>

  <!-- table区域-begin -->
  <BasicTable @register="registerTable" :rowSelection="rowSelection">
    <!--插槽:table标题
    <template #tableTitle></template> -->
  </BasicTable>
  <!-- table区域-end -->

  <!-- 表单区域 -->
  <AccountOnPaymentModal @register="registerAccountOnPaymentModal" @success="handleSubmit"></AccountOnPaymentModal>
  <AccountFlowTakeDataGrid @register="registerAccountFlowTakeDataGrid"></AccountFlowTakeDataGrid>
</template>

<script lang="ts" setup name="account-onPaymentList">
import { ref, computed, unref, reactive, toRaw, onMounted, nextTick, defineAsyncComponent } from "vue";
import { BasicTable, TableAction, ActionItem, BasicColumn } from "/@/components/Table";
import { useModal } from "/@/components/Modal";
import { useListPage } from "/@/hooks/system/useListPage";
import { render } from "/@/utils/common/renderUtils";
import { onPaymentList, countbackRecord } from "/@/views/full/account/types/accountflow.api";
import { useMessage } from "/@/hooks/web/useMessage";
import { momentSearchQueryDate } from "/@/utils/dateUtil";
import { Cascader } from 'ant-design-vue';
import { coopSelect } from "/@/views/full/business/business.api";
import moment from 'dayjs'
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import AccountOnPaymentModal from './modules/AccountOnPaymentModal.vue';
import AccountFlowTakeDataGrid from './AccountFlowTakeDataGrid.vue';
import { count } from "/@/views/full/account/types/AccountPrint.api";
import { filterObj } from "/@/utils/common/compUtils";
import { useUserStore } from '/@/store/modules/user';
//const AccountFlowTakeDataGrid = defineAsyncComponent(() => import('/@/full/account/AccountFlowTakeDataGrid.vue'))

const userStore = useUserStore();
const { createMessage: $message } = useMessage();
//初始化 -------------------------------------------------------------
//定义查询表单，查询条件
const queryParam = reactive({
  ddlxIds: [],
  stat: '1', //未审
  sffs: '', //方式
  beginDate : momentSearchQueryDate('sub'),
  endDate: momentSearchQueryDate('add'),
  coopId: '',
  orderId: '',
  travelLine: '',
  jqchecked: '0',
});
let backCn = ref<number>(0);

/* 日期参数 */
function disabledStartDate(beginDate) {
  const endDate = queryParam.endDate
  if (!beginDate || !endDate) {
    return false
  }
  return beginDate.valueOf() > moment(endDate).valueOf()
}

function disabledEndDate(endDate) {
  const beginDate = queryParam.beginDate
  if (!endDate || !beginDate) {
    return false
  }
  return moment(beginDate).valueOf() > endDate.valueOf()
}

//订单列表
const statusFmt = ({text}: { text: any }) => {
  const color = text == '1' ? 'green' : text == '2' ? 'red' : 'gray';
  return render.renderTag(render.renderDict(text, 'accountStat'), color)
}

const sffsFmt = ({text}: { text: any }) => {
  if (!text) {
    return
  }
  // 0 未选择 1、转账，2现多，1 挂账 2 划转 3 现金 4 转账 5 其他
  let color : String[] = ['', 'red', '', 'blue', 'purple', 'orange'];
  return render.renderTag(render.renderDict(text, 'sffsType'), color[text])
}

//订单列表 - 表头
const columns: BasicColumn[] = [
  { title: "状态", align: "center", dataIndex: "stat", width: 50, customRender: statusFmt,},
  { title: "部门", align: "center", dataIndex: "ddlx", width: 70, customRender:({text}) => render.renderDict(text, 'ddlxType') },
  { title: "订单号", align: "center", dataIndex: "orderId", width: 95, className: "text-red-500" },
  { title: "采购单位", align: "left", dataIndex: "pathName", width: 150 },
  { title: '方式', align: 'center', dataIndex: 'sffs', width: 45, customRender: sffsFmt },
  { title: "付款金额", align: "right", dataIndex: "fkje", width: 80, className: "text-indigo-600" },
  { title: "应收", align: "right", dataIndex: "ygs", width: 80, className: "text-red-500" },
  { title: "应付", align: "right", dataIndex: "ygf", width: 80, className: "text-green-500" },
  { title: "已收", align: "right", dataIndex: "yjs", width: 80, className: "text-red-500" },
  { title: "已付", align: "right", dataIndex: "yjf", width: 80, className: "text-green-500" },
  { title: "利润", align: "right", dataIndex: "lr", width: 80, className: "text-blue-500" },
  { title: "操作人", align: "center", dataIndex: "realname", width: 55 },
  { title: "提交日期", align: "center", dataIndex: "lrsj", width: 80, format: "date|YYYY-MM-DD" },
]
//初始化 -------------------------------------------------------------
// 列表页面公共参数、方法
const {prefixCls, tableContext, onImportXls} = useListPage({
  designScope: 'account-onPaymentList',
  tableProps: {
    rowKey: "id",
    api: onPaymentList,
    columns: columns,
    showTableSetting: false,
    showIndexColumn: false,    //行号
    clickToRowSelect: true,    //点击选择
    showActionColumn: false,
    useSearchForm: false,
    pagination: {
      current: 1,
      pageSize: 100,
      pageSizeOptions: ['100', '300', '500'],
    },
    beforeFetch: (params) => Object.assign(params, unref(queryParam)),
  },
})
//注册table数据 rowSelection, selectedRowKeys, selectedRows
const [registerTable, {reload, setProps, getRawDataSource, setSelectedRowKeys, redoHeight}, { rowSelection, selectedRowKeys, selectedRows }] = tableContext

function searchQuery() {
  setSelectedRowKeys([]);
  setProps({ searchInfo: toRaw(queryParam) });
  reload()
  getBackCn()
}

function handleSubmit() {
  searchQuery()
}
//提交
const [registerAccountOnPaymentModal, {openModal: openAccountOnPaymentModal} ] =  useModal()

//提交
function auditALLSelect(record) {
  //1、获取被选中的行信息
  let rows = unref(selectedRows)
  if (rows.length <= 0) {
    $message.warning("请选择") //请勾选不能为空！
    return false
  }

  //2、判断选中的单位是否是同一家
  var pId = [], ids = ''; //, sffsArray = []
  for (var i = 0; i < rows.length; i++) {
    pId.push(rows[i].coopId)
    //sffsArray.push(rows[i].sffs) // 方式
    if (i == 0) {
      ids = rows[i].id;
    } else {
      ids = ids + "," + rows[i].id;
    }
  }
  if (pId.length > 0 && userStore.getTenant == 1) {
    pId = pId.sort()
    for (var i = 0; i < pId.length - 1; i++) {
      if (pId[i] != pId[i + 1]) {
        $message.warning('请选择同一家供应商，进行付款款申请审核操作！')
        return false
      }
    }
  }
  // if (sffsArray.length > 0 && userStore.getTenant == 1) {
  //   sffsArray = sffsArray.sort()
  //   for (var i = 0; i < sffsArray.length - 1; i++) {
  //     if (sffsArray[i] != sffsArray[i + 1]) {
  //       $message.warning('请选择同一种收付方式！')
  //       return false
  //     }
  //   }
  // }
  //console.info(selectedRows)
  openAccountOnPaymentModal(true, {ids});
}

const cascader = reactive<any>({
  ids: [],
  options: []
});

function cooperatorSelect(value) {
  //console.info("coopOptions", value, cascader.ids)
  if (!value && value.length < 3) {
    return false
  }
  queryParam.coopId = value[2];
}

const filter = (inputValue: string, path) => {
  return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
}

//挂账
const [registerAccountFlowTakeDataGrid, {openModal: openAccountFlowTakeDataGrid} ] =  useModal()
function handAccountFlowTakeDataGrid(stat) {
  openAccountFlowTakeDataGrid(true, {stat});
}

onMounted(async () => {
  await nextTick()
  let res = await coopSelect()
  Object.assign(cascader.options, res)
  getBackCn()
});

function getBackCn() {
  countbackRecord(queryParam).then((res) => {
    backCn.value = res;
  });
}

</script>
<style scoped>

</style>
